﻿CREATE PROCEDURE [dbo].[RepriceLinesUpdate] --переоценка товара
(
	@DocId int,
	@NewRetailPrice decimal(19,2),  --новая цена
	@Qntty int,											--количество товара, который переоценивается
	@NewBarCode char(12),
	@RepriceWriteoffReasonId int, --код причины списания/переоценки
	@RepriceWriteoffReasonText varchar(50),--причина для кода 4 
	@QualityLossMark varchar(50), --признак понижения качества
	@Note varchar(250),
	@MW varchar(50),
	@MD datetime,
	@Original_Id int,				--код строки в таблице списания/переоценки 
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intRowCount int
DECLARE @intOldPartyId int, @intNewPartyId int, @orgQntty int
DECLARE @orgNewPrice decimal(19,2), @orgOldPrice decimal(19,2), @orgBarCode char(12)
DECLARE @intSumGoodsFlow int, @intPartyRest int, @datDocDate smalldatetime
DECLARE @intNLId int, @intOLId int
DECLARE @intT int, @strBarCode char(12), @intInputLineId int, @intGoodsId int, @intReturnLineId int 
DECLARE @intInputCount int, @intOutputCount int

SET NOCOUNT ON

IF (@DocId Is Null) OR (@NewRetailPrice Is Null) OR (@NewRetailPrice <= 0 ) 
OR (@Qntty Is Null) OR (@Qntty <= 0 ) OR (@RepriceWriteoffReasonId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intOldPartyId = OldPartyId, @intNewPartyId = NewPartyId, @orgQntty = Qntty, 
@orgOldPrice = OldPrice, @orgNewPrice = NewRetailPrice, @orgBarCode = NewBarCode,
@intOLId = OLId, @intNLId = NLId
FROM dbo.vwRepriceLines WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intPartyRest = RestQntty, @intGoodsId = GoodsId,
@intInputLineId = InputLineId
FROM CD.Parties WHERE Id = @intOldPartyId

IF (@NewRetailPrice = @orgOldPrice) 
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Новая цена равна старой цене!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intT = DocTypeId, @datDocDate = DocDate FROM [CA].[Documents] WHERE Id = @DocId
IF (@intT Is Null)
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Не найден документ с идентификатором ' + cast(@DocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@intT <> 10)
BEGIN
	SELECT @intErrCode = 5, @strMsg = 'Неправильный тип документа с идентификатором ' + cast(@DocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

-- проверка товародвижения по партии, которая переоценивается
SET @intT = -1 * (@Qntty - @orgQntty)
EXEC @intRet = dbo.CheckPartyFlow @intOldPartyId, @intT, @datDocDate, @intInputCount OUTPUT, @intOutputCount OUTPUT
IF @intRet <> 0 RETURN @intRet

IF (@NewBarCode Is Null) EXEC [dbo].[GetNextBarCode] @NewBarCode OUTPUT
EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

BEGIN TRAN

IF (@orgQntty <> (0 - @Qntty) )--измененение расхода по исходной партии
BEGIN
	UPDATE [CA].[GoodsDocLines] SET
	[Qntty] = -1 * @Qntty, 
	[RetailSum] = @orgOldPrice * -1.0 * @Qntty, 
	[MD] = @MD, [MW] = @MW 
	WHERE Id = @intOLId

	SELECT @intErrCode = @@error, @intRowCount = @@rowcount

	IF @intErrCode <> 0 
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		RETURN @intErrCode
	END
	IF (@intRowCount <> 1)
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		SELECT @intErrCode = 6, 
		@strMsg = 'Запись по исходной партии в таблице товародвижения не изменена!'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END

END

IF (@orgNewPrice <> @NewRetailPrice) OR ( @orgBarCode = @NewBarCode)
BEGIN --измененение цены или штрихкода по новой партии 
	UPDATE CD.Parties SET
	[BarCode] = @NewBarCode, 
	[RetailPrice] = @NewRetailPrice,
	[MD] = @MD, [MW] = @MW 
	WHERE Id = @intNewPartyId

	SELECT @intErrCode = @@error, @intRowCount = @@rowcount

	IF @intErrCode <> 0 
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		RETURN @intErrCode
	END
	IF (@intRowCount <> 1)
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		SELECT @intErrCode = 7, 
		@strMsg = 'Запись по новой партии не изменена!'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END

END

IF (@orgNewPrice <> @NewRetailPrice) OR (@orgQntty <> (0 - @Qntty) )
BEGIN --измененение прихода по новой партии

	UPDATE [CA].[GoodsDocLines] SET
	[Qntty] = @Qntty, 
	[RetailSum] = @NewRetailPrice * @Qntty, 
	[MD] = @MD, [MW] = @MW 
	WHERE Id = @intNLId

	SELECT @intErrCode = @@error, @intRowCount = @@rowcount

	IF @intErrCode <> 0 
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		RETURN @intErrCode
	END
	IF (@intRowCount <> 1)
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		SELECT @intErrCode = 8, 
		@strMsg = 'Запись по новой партии в таблице товародвижения не изменена!'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END

END

	SET NOCOUNT OFF;

UPDATE CD.RepriceWriteoffLines SET 
RepriceWriteoffReasonId = @RepriceWriteoffReasonId,
RepriceWriteoffReasonText = @RepriceWriteoffReasonText,
QualityLossMark = @QualityLossMark,
[Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id ;

SELECT @intErrCode = @@error, @intRowCount = @@rowcount

	SET NOCOUNT ON;

IF @intErrCode <> 0 
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	RETURN @intErrCode
END
IF (@intRowCount <> 1)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 9, 
	@strMsg = 'Запись в таблице списания/переоценки не изменена!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

COMMIT TRAN

SELECT Id, DocId, GoodsId, OldPartyId, OldPrice, OldBarCode, Qntty, NewPartyId, NewRetailPrice, NewBarCode, 
RepriceWriteoffReasonId, RepriceWriteoffReasonName, 
RepriceWriteoffReasonText, QualityLossMark,
Note, MD, MW
FROM dbo.vwRepriceLines WHERE Id = @Original_Id

RETURN 0
